package com.lvyq.config;
import com.alibaba.fastjson.JSONObject;
import com.lvyq.cache.CacheManager;
import com.lvyq.common.api.APITypeConstant;
import com.lvyq.model.apiinfo.ApiInfo;
import com.lvyq.model.receive.ReceiveMsg;
import com.lvyq.repository.api.ApiInfoRepository;
import com.lvyq.util.TCGPTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lvyq
 * @version 1.0
 * @description: TODO
 * @date 2021/8/17 16:30
 */
@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {

     private static ApiInfoRepository apiInfoRepository;
    @Autowired
    public  void setChatService(ApiInfoRepository apiInfoRepository) {
        WebSocketServer.apiInfoRepository = apiInfoRepository;
    }
    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SessionSet.add(session);
        int cnt = OnlineCount.incrementAndGet();
        log.info("有连接加入，当前连接数为：{}", cnt);
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
      //  log.info("来自客户端的消息：{}",message);
        try{
            JSONObject jsonObject = JSONObject.parseObject(message);
            String post_type = jsonObject.getString("post_type");
            String msg= jsonObject.getString("message");
            if (post_type.equals("message") && msg.startsWith("G#") ){
                String [] contents = msg.split("#");
                ApiInfo apiInfo = apiInfoRepository.findByType(APITypeConstant.GPT);
                String replyContent= TCGPTUtil.getAnswer(apiInfo,contents[1]);
                //消息
                ReceiveMsg receiveMsg =new ReceiveMsg();
                receiveMsg.setContent(msg);
                receiveMsg.setFromUserName("oRIyD5xBjkdNQ4HqohqPhVbIcYu8");
                receiveMsg.setMsgId("1");
               // String m=orderService.orderReply(receiveMsg);
                JSONObject mav = new JSONObject();
                mav.put("message_type","group");
                mav.put("user_id",1540194374);
                mav.put("group_id",495673338);
                mav.put("message",replyContent);
                mav.put("auto_escape",false);
                sendPost("http://127.0.0.1:5700/send_msg",mav.toJSONString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            //session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
            log.info("sessionID="+session.getId());
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessageById(String message,String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }
    /**
     * @description: 指定发送
     * @author: lvyq
     * @date: 2021/9/24 11:30
     * @version 1.0
     */
    public static void SendMessageByRecId(String message,String receiveId) throws IOException {
        Session session=  CacheManager.get("bind_"+receiveId);
        String sessionId = "";
        if (session!=null){
            sessionId=session.getId();
        }
        for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }
    public void sendPost( String url,String param) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type","application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            out.print(param);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(conn.getInputStream())); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var16) {
            System.out.println("发送 POST 请求出现异常！" + var16);
            var16.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

    }

}
